function [ T , pval ] = conover(data, belong)
% ------------------------------------------------------------------------------------
%   Variance Test for Several Populations
%   Input:  data - samples concatenated together, data vector. 
%           belong - treatment groups for elements in the data vector;
%   
%   Output: T - Test statistics;
%           p - p-value for testing equality of variances
%           
%   Example of use:
%  
%  >> data  =  [ 1 3 4  3 4 5  4 4 4 6 5 ];
%  >> belong = [ 1 1 1  2 2 2  3 3 3 3 3 ]; 
%  >> [T, p] = conover(data, belong)
%   Needs: M-FILES ranks.m , tie.m, and diffferent.m  
%-------------------------------------------------------------------------------------
data = data(:)';      
  m = length( data );   
belong = belong(:)' ;      
N = length( belong ); 

if m ~= N 
    error('DATA and BELONG should be paired.')
end

di = different(belong);     k = length(di);     cnt = [];
for j = 1 : k
    cnt = [cnt; sum(di(j,1) == belong)];
end

ed = 0;     means = [];
for j = 1 : k
    st = ed+1;  
    ed = ed + cnt(j,1);
    means = [means mean(data(1,st:ed))];
end

xbar = [];
for j = 1 : k
    xbar = [xbar means(1,j)*ones(1,cnt(j,1))];
end

xij = (data - xbar).^2;     Ra = (ranks(xij));   
Ra2 = Ra.^2;        Ra4 = Ra.^4;
Ti = [];  
for i = 1 : k
    Ti = [Ti sum(Ra2(belong==di(i,1)))];
end
Tbar = mean(Ra2);       %Tbar = mean(Ti)
VT = (sum(Ra4) - N*Tbar^2)/(N-1);
T = (sum((Ti.^2)./cnt') - N*Tbar^2)/VT;
pval = 1-chi2cdf(T, k-1);
